package com.tanjun.web.config;

import com.tanjun.common.constants.HeaderConstant;
import feign.RequestInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

//import jakarta.servlet.http.HttpServletRequest;

/**
 * 调用其他服务将header中用户信息传递出去
 */
@Slf4j
@Configuration
public class FeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes)
                    RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                // 从当前请求中获取网关传递的头部
                log.info("[feign add header],userInfo:{},userRoles:{},loginTerminal:{},permissionVersion:{},userType:{},adminUserType:{}",
                        request.getHeader(HeaderConstant.USER_INFO),
                        request.getHeader(HeaderConstant.USER_ROLES),
                        request.getHeader(HeaderConstant.LOGIN_TERMINAL),
                        request.getHeader(HeaderConstant.USER_PERMISSION),
                        request.getHeader(HeaderConstant.USER_TYPE),
                        request.getHeader(HeaderConstant.ADMIN_USER_TYPE)
                        );
                // 将头部添加到请求中
                requestTemplate.header(HeaderConstant.USER_TYPE,request.getHeader(HeaderConstant.USER_INFO));
                requestTemplate.header(HeaderConstant.USER_TYPE,request.getHeader(HeaderConstant.USER_TYPE));
                requestTemplate.header(HeaderConstant.ADMIN_USER_TYPE,request.getHeader(HeaderConstant.ADMIN_USER_TYPE));
                requestTemplate.header(HeaderConstant.USER_ROLES, request.getHeader(HeaderConstant.USER_ROLES));
                requestTemplate.header(HeaderConstant.LOGIN_TERMINAL,request.getHeader(HeaderConstant.LOGIN_TERMINAL));
                requestTemplate.header(HeaderConstant.USER_PERMISSION,request.getHeader(HeaderConstant.USER_PERMISSION));
            }
        };
    }
}
